﻿using Noesis.Javascript;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace MO.BusinessServer
{
    public class FormManager : BaseManager
    {
        public FormManager(object context)
        {
            base.Init(context);
        }
        public FormJson GetForm(string formCode, string dataCode)
        {
            if (string.IsNullOrEmpty(dataCode))
                return GetForm(formCode);
            FormDefine fd = DataManager.FindFormByFormCode(formCode);
            var list = DataManager.FindFormItemByFormCode(fd.Code);
            var dict = DataManager.FindDataByTableCode(fd.EntityCode, dataCode);
            foreach (var item in list)
            {
                if (!string.IsNullOrEmpty(item.ControlSources))
                    item.ControlData = RunScript(item.ControlSources);
                if (!string.IsNullOrEmpty(item.FieldCode))
                {
                    FieldDefine field = DataManager.FindFieldByFieldCode(item.FieldCode);
                    if (string.IsNullOrEmpty(field.Reference))
                        item.DefaultValue = dict[item.FieldCode];
                    else
                    {
                        string rc = dict[item.FieldCode].ToString();
                        if (!string.IsNullOrEmpty(rc))
                            item.DefaultValue = DataManager.FindDataByTableCode(field.Reference, rc)[field.Reference + "_NAME"];
                    }
                }
            }
            FormJson json = new FormJson(fd);
            json.Items = list;
            return json;
        }
        public FormJson GetForm(string formCode)
        {
            if (string.IsNullOrEmpty(formCode))
                return null;
            FormDefine fd = DataManager.FindFormByFormCode(formCode);
            var list = DataManager.FindFormItemByFormCode(fd.Code);
            foreach (var item in list)
            {
                if (!string.IsNullOrEmpty(item.ControlSources))
                    item.ControlData = RunScript(item.ControlSources);
                if (item.DefaultValue != null && item.DefaultValue.ToString() != "")
                    item.DefaultValue = RunScript(item.DefaultValue.ToString());
            }
            FormJson json = new FormJson(fd);
            json.Items = list;
            return json;
        }
        public void SubmitForm(string formCode, Dictionary<string, string> dict)
        {
            FormDefine fd = DataManager.FindFormByFormCode(formCode);
            var itemDict = DataManager.FindFormItemByFormCode(formCode).ToDictionary(k => k.Code, v => v);
            List<ItemData> items = new List<ItemData>();
            foreach (var key in dict.Keys)
            {
                ItemData item = new ItemData();
                item.FormItem = itemDict[key];
                string value = dict[key];
                if (item.FormItem.ControlType == ControlType.Img)
                {
                    if (!string.IsNullOrEmpty(value))
                    {
                        string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + Guid.NewGuid().To16String() + ".jpg";
                        File.WriteAllBytes(string.Format("{0}\\Upload\\{1}", ConfigAccess.RunPath, fileName), Convert.FromBase64String(value));
                        value = fileName;
                    }
                }
                item.value = value;
                item.FieldDefine = DataManager.FindFieldByFieldCode(item.FormItem.FieldCode);
                items.Add(item);
            }
            // 字段对应的值
            Dictionary<string, object> formData = items.ToDictionary(k => k.FieldDefine.Code, v => (object)v.value);
            string tableName = fd.EntityCode;
            formData["__TableName"] = tableName;
            SysOperation sys = new SysOperation() { User = this.Context.User };
            JavascriptContext context = new JavascriptContext();
            context.SetParameter(tableName, formData);
            context.SetParameter("Sys", sys);
            context.Run(fd.SubmitScript);
            //FlowManager.SubmitForm(formCode, items.ToDictionary(k => k.FieldDefine.Code, v => (object)v.value), this.Context.User);
            //Dictionary<string, List<ItemData>> dict = items.GroupBy(t => t.FieldDefine.EntityCode).ToDictionary(k => k.Key, v => v.ToList());

        }
        object RunScript(string script)
        {
            JavascriptContext context = new JavascriptContext();
            SysOperation sys = new SysOperation() { User = this.Context.User };
            context.SetParameter("Sys", sys);
            script = "var data = " + script;
            context.Run(script);
            return context.GetParameter("data");
        }
    }
    class ItemData
    {
        public FormItem FormItem;
        public FieldDefine FieldDefine;
        public string value;
    }
    public class FormJson
    {
        public string Code;
        public string Name;
        public string Description;
        public string ViewTemplate;
        public string ViewScript;
        public List<FormItem> Items;
        public FormJson(FormDefine form)
        {
            this.Code = form.Code;
            this.Name = form.Name;
            this.Description = form.Description;
            this.ViewTemplate = form.ViewTemplate;
            this.ViewScript = form.ViewScript;
        }
    }
}
